﻿using System.Data;
using System.Linq;
using EmployeesManager.Poco;
using EmployeesManagerDataAccessContracts;

namespace Employeesmanager.DataAccessEF
{
    public class EmployeesDb : IRepository<Employee>
    {
        private EmployeesContext db = new EmployeesContext();

        public System.Linq.IQueryable<Employee> Entities{ get { return db.Employees.AsNoTracking().Include("Manager"); } set { } }

        public bool Save(Employee entity)
        {
            entity.Manager = null;
            if (entity.Id > 0)
            {
                db.Employees.Attach(entity);
                db.Entry(entity).State = EntityState.Modified;
            }
            else
            {
                db.Employees.Add(entity);
            }
            var ret = db.SaveChanges() > 0;
            entity.Manager = db.Employees.AsNoTracking().Include("Manager").FirstOrDefault(c => c.Id == entity.ManagerId);
            return ret;
        }

        public bool Delete(int id)
        {
            var emp = new Employee { Id = id };
            db.Employees.Attach(emp);
            db.Employees.Remove(emp);
            return db.SaveChanges() > 0;
        }

    }
}